import axios from 'axios'
import router from '../router'
import { ElMessage } from 'element-plus'

//创建axios实例对象
const request = axios.create({
  baseURL: '/api',
  timeout: 600000
})

//axios的请求 request 拦截器
request.interceptors.request.use(
  (config) => { //成功回调
    const loginUserStr = localStorage.getItem('loginUser')
    if (loginUserStr) {
      const loginUser = JSON.parse(loginUserStr)
      config.headers['token'] = loginUser.token
    }
    return config
  },
  (error) => { //失败回调
    return Promise.reject(error)
  }
)

//axios的响应 response 拦截器
request.interceptors.response.use(
  (response) => { //成功回调
    return response.data
  },
  (error) => { //失败回调
    //判断后端响应状态是不是401
    if (error.response.status === 401) {
      //清除token
      localStorage.removeItem('loginUser')
      //跳转到登录页面
      router.push('/login')
      //给个提示
      ElMessage.error('登录过期,请重新登录')
    }
    return Promise.reject(error)
  }
)

export default request